<template>
	<view class="search-page">
		<!-- 搜索头部 -->
		<view class="search-header" :style="{ paddingTop: safeAreaInsets.top +40+ 'px' }">
			<view class="search-bar" :class="{ 'search-focused': searchFocused }">
				<!-- 返回按钮 -->
				<view class="back-button" @click="goBack">
					<uni-icons type="back" size="20" color="#666"></uni-icons>
				</view>
				<!-- 自定义搜索输入框 -->
				<view class="search-input-wrapper">
					<uni-icons type="search" size="16" color="#999" class="search-icon"></uni-icons>
					<input v-model="searchKeyword" class="search-input" placeholder="搜索帖子、圈子或用户" @input="handleInput"
						@focus="handleFocus" @blur="handleBlur" @confirm="handleSearch" confirm-type="search"
						:focus="autoFocus" />
					<!-- 清除按钮 -->
					<view v-if="searchKeyword" class="clear-button" @click="handleClear">
						<uni-icons type="clear" size="14" color="#999"></uni-icons>
					</view>
				</view>
				<!-- 搜索建议 -->
				<SearchSuggestions :visible="showSuggestions" :suggestions="searchSuggestions"
					@suggestionClick="handleSuggestionClick" />
			</view>
		</view>

		<!-- 搜索历史 -->
		<view class="search-history" v-if="!hasSearched && searchHistory.length > 0">
			<view class="history-header">
				<text class="history-title">搜索历史</text>
				<text class="history-clear" @click="clearHistory">清空</text>
			</view>
			<view class="history-tags">
				<view class="history-tag" v-for="(item, index) in searchHistory" :key="index"
					@click="searchFromHistory(item)">
					{{ item }}
				</view>
			</view>
		</view>

		<!-- 热门搜索 -->
		<view class="hot-search" v-if="!hasSearched">
			<view class="hot-header">
				<text class="hot-title">热门搜索</text>
			</view>
			<view class="hot-tags">
				<view class="hot-tag" v-for="(item, index) in hotSearchKeywords" :key="index"
					@click="searchFromHot(item)">
					{{ item }}
				</view>
			</view>
		</view>

		<!-- 搜索结果 -->
		<view class="search-results" v-if="hasSearched">
			<!-- 结果分类选项卡 -->
			<view class="result-tabs">
				<view class="tab-item" :class="{ active: activeTab === 'all' }" @click="switchTab('all')">
					全部({{ totalCount }})
				</view>
				<view class="tab-item" :class="{ active: activeTab === 'posts' }" @click="switchTab('posts')">
					帖子({{ postResults.length }})
				</view>
				<view class="tab-item" :class="{ active: activeTab === 'circles' }" @click="switchTab('circles')">
					圈子({{ circleResults.length }})
				</view>
				<view class="tab-item" :class="{ active: activeTab === 'users' }" @click="switchTab('users')">
					用户({{ userResults.length }})
				</view>
			</view>

			<!-- 搜索结果内容 -->
			<view class="result-content">
				<!-- 加载状态 -->
				<view class="loading" v-if="isLoading">
					<uni-load-more status="loading" />
				</view>

				<!-- 无结果 -->
				<SearchEmpty v-else-if="totalCount === 0" :title="'没有找到关于' + lastSearchKeyword + '的内容'"
					:subtitle="'试试其他关键词或者浏览热门内容'" :suggestions="hotSearchKeywords.slice(0, 5)"
					@suggestionClick="searchFromHot" />

				<!-- 结果列表 -->
				<template v-else>
					<!-- 全部结果 -->
					<template v-if="activeTab === 'all'">
						<!-- 帖子结果 -->
						<view class="result-section" v-if="postResults.length > 0">
							<view class="section-header">
								<text class="section-title">帖子</text>
								<text class="section-more" @click="switchTab('posts')">查看更多</text>
							</view>
							<WaterfallList :posts="postResults.slice(0, 4)" :itemWidth="itemWidth"
								@postClick="handlePostClick" />
						</view>

						<!-- 圈子结果 -->
						<view class="result-section" v-if="circleResults.length > 0">
							<view class="section-header">
								<text class="section-title">圈子</text>
								<text class="section-more" @click="switchTab('circles')">查看更多</text>
							</view>
							<view class="circle-list">
								<CircleCard v-for="circle in circleResults.slice(0, 3)" :key="circle.id"
									:circle="circle" @click="handleCircleClick" />
							</view>
						</view>

						<!-- 用户结果 -->
						<view class="result-section" v-if="userResults.length > 0">
							<view class="section-header">
								<text class="section-title">用户</text>
								<text class="section-more" @click="switchTab('users')">查看更多</text>
							</view>
							<view class="user-list">
								<UserCard 
									v-for="user in userResults.slice(0, 3)" 
									:key="user.userId" 
									:user="user"
									:isFollowing="checkIsFollowing(user.userId)"
									:followId="getFollowId(user.userId)"
									@click="handleUserClick" 
									@followChange="handleFollowChange"
								/>
							</view>
						</view>
					</template>

					<!-- 帖子结果 -->
					<WaterfallList v-else-if="activeTab === 'posts'" :posts="postResults" :itemWidth="itemWidth"
						@postClick="handlePostClick" />

					<!-- 圈子结果 -->
					<view v-else-if="activeTab === 'circles'" class="circle-list">
						<CircleCard v-for="circle in circleResults" :key="circle.id" :circle="circle"
							@click="handleCircleClick" />
					</view>

					<!-- 用户结果 -->
					<view v-else-if="activeTab === 'users'" class="user-list">
						<UserCard 
							v-for="user in userResults" 
							:key="user.userId" 
							:user="user"
							:isFollowing="checkIsFollowing(user.userId)"
							:followId="getFollowId(user.userId)"
							@click="handleUserClick" 
							@followChange="handleFollowChange"
						/>
					</view>
				</template>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed, onMounted } from 'vue'
	import { queryCircleByCircleName, type CircleBasicInfo } from '@/api/circle/circle'
	import { getPostByPostTitle, type PostBasicInfo } from '@/api/post/post'
	import { getUserByNickName } from '@/api/user/user'
	// 添加关注相关的导入
	import { getFollowedByFansId, type UserFollowVO } from '@/api/follow/follow'
	import useUserStore from '@/store/modules/user'
	import WaterfallList from '@/components/post/WaterfallList.vue'
	import CircleCard from '@/pages/circle/components/CircleCard.vue'
	import UserCard from './components/UserCard.vue'
	import SearchEmpty from './components/SearchEmpty.vue'
	import SearchSuggestions from './components/SearchSuggestions.vue'

	// 获取屏幕边界到安全区域距离
	const { safeAreaInsets } = uni.getWindowInfo()
	// 添加用户store
	const userStore = useUserStore()
	const currentUser = computed(() => userStore.user)

	// 响应式数据
	const searchKeyword = ref('')
	const lastSearchKeyword = ref('')
	const hasSearched = ref(false)
	const isLoading = ref(false)
	const activeTab = ref<'all' | 'posts' | 'circles' | 'users'>('all')
	const searchFocused = ref(false)
	const autoFocus = ref(true)
	const showSuggestions = ref(false)

	// 搜索结果
	const postResults = ref<PostBasicInfo[]>([])
	const circleResults = ref<CircleBasicInfo[]>([])
	const userResults = ref<any[]>([])
	// 添加关注列表
	const followingList = ref<UserFollowVO[]>([])

	// 搜索历史和建议
	const searchHistory = ref<string[]>([])
	const searchSuggestions = ref<any[]>([])

	// 防抖定时器
	let searchTimer : number | null = null

	// 热门搜索关键词
	const hotSearchKeywords = ref([
		'科技', '生活', '美食', '旅行', '音乐',
		'电影', '读书', '健身', '摄影', '游戏'
	])

	// 计算属性
	const totalCount = computed(() => {
		return postResults.value.length + circleResults.value.length + userResults.value.length
	})

	const itemWidth = computed(() => {
		const systemInfo = uni.getSystemInfoSync()
		return (systemInfo.windowWidth - 64) / 2 // 减去padding和gap
	})

	// 生命周期
	onMounted(() => {
		loadSearchHistory()
		// 加载当前用户的关注列表
		loadFollowingList()
	})

	// 添加加载关注列表的方法
	const loadFollowingList = async () => {
		if (!currentUser.value?.userId) return
		
		try {
			const result = await getFollowedByFansId(currentUser.value.userId)
			followingList.value = result.data || []
		} catch (error) {
			console.error('加载关注列表失败:', error)
		}
	}

	// 添加检查关注状态的方法
	const checkIsFollowing = (targetUserId: number): boolean => {
		return followingList.value.some(item => item.followedUserId === targetUserId)
	}

	// 添加获取关注记录ID的方法
	const getFollowId = (targetUserId: number): number | undefined => {
		const followItem = followingList.value.find(item => item.followedUserId === targetUserId)
		return followItem?.id
	}

	// 添加处理关注状态变化的方法
	const handleFollowChange = async (targetUserId: number, isFollowing: boolean, followId?: number) => {
		if (isFollowing) {
			// 添加到关注列表
			if (followId) {
				followingList.value.push({
					id: followId,
					followedUserId: targetUserId,
					fansId: currentUser.value.userId
				} as UserFollowVO)
			}
		} else {
			// 从关注列表中移除
			followingList.value = followingList.value.filter(item => item.followedUserId !== targetUserId)
		}
	}

	const handleSearch = () => {
		if (!searchKeyword.value.trim()) {
			uni.showToast({
				title: '请输入搜索关键词',
				icon: 'none'
			})
			return
		}
		performSearch(searchKeyword.value.trim())
	}

	const performSearch = async (keyword : string) => {
		isLoading.value = true
		hasSearched.value = true
		lastSearchKeyword.value = keyword
		showSuggestions.value = false

		try {
			// 保存搜索历史
			saveSearchHistory(keyword)

			// 并发搜索所有类型
			const [postResponse, circleResponse, userResponse] = await Promise.allSettled([
				getPostByPostTitle(keyword),
				queryCircleByCircleName(keyword),
				getUserByNickName(keyword)
			])

			// 处理帖子搜索结果
			if (postResponse.status === 'fulfilled' && postResponse.value.code === 200) {
				postResults.value = postResponse.value.rows || []
			} else {
				postResults.value = []
			}

			// 处理圈子搜索结果
			if (circleResponse.status === 'fulfilled' && circleResponse.value.code === 200) {
				const circles = circleResponse.value.rows
				circleResults.value = Array.isArray(circles) ? circles : circles ? [circles] : []
			} else {
				circleResults.value = []
			}

			// 处理用户搜索结果
			if (userResponse.status === 'fulfilled' && userResponse.value.code === 200) {
				const users = userResponse.value.rows
				userResults.value = Array.isArray(users) ? users : users ? [users] : []
			} else {
				userResults.value = []
			}

		} catch (error) {
			console.error('搜索失败:', error)
			uni.showToast({
				title: '搜索失败，请重试',
				icon: 'none'
			})
		} finally {
			isLoading.value = false
		}
	}

	const handleClear = () => {
		searchKeyword.value = ''
		showSuggestions.value = false
		hasSearched.value = false
	}

	const handleInput = (e : any) => {
		const value = e.detail.value
		if (value.trim()) {
			// 防抖搜索建议
			if (searchTimer) {
				clearTimeout(searchTimer)
			}
			searchTimer = setTimeout(() => {
				generateSearchSuggestions(value)
			}, 300)
		} else {
			showSuggestions.value = false
		}
	}

	const handleFocus = () => {
		searchFocused.value = true
		if (searchKeyword.value.trim()) {
			generateSearchSuggestions(searchKeyword.value)
		}
	}

	const handleBlur = () => {
		// 延迟隐藏建议，确保用户能点击建议项
		setTimeout(() => {
			searchFocused.value = false
			showSuggestions.value = false
		}, 200)
	}

	const handleSuggestionClick = (suggestion : any) => {
		searchKeyword.value = suggestion.text
		performSearch(suggestion.text)
	}

	const generateSearchSuggestions = (keyword : string) => {
		// 生成搜索建议（实际项目中应该调用后端接口）
		const suggestions = []

		// 从搜索历史中匹配
		searchHistory.value.forEach(item => {
			if (item.includes(keyword) && item !== keyword) {
				suggestions.push({
					text: item,
					type: '搜索历史'
				})
			}
		})

		// 从热门搜索中匹配
		hotSearchKeywords.value.forEach(item => {
			if (item.includes(keyword) && item !== keyword) {
				suggestions.push({
					text: item,
					type: '热门搜索'
				})
			}
		})

		// 限制建议数量
		searchSuggestions.value = suggestions.slice(0, 8)
		showSuggestions.value = suggestions.length > 0
	}

	const switchTab = (tab : 'all' | 'posts' | 'circles' | 'users') => {
		activeTab.value = tab
	}

	const searchFromHistory = (keyword : string) => {
		searchKeyword.value = keyword
		performSearch(keyword)
	}

	const searchFromHot = (keyword : string) => {
		searchKeyword.value = keyword
		performSearch(keyword)
	}

	const saveSearchHistory = (keyword : string) => {
		// 移除重复项
		const newHistory = searchHistory.value.filter(item => item !== keyword)
		// 添加到开头
		newHistory.unshift(keyword)
		// 限制历史记录数量
		if (newHistory.length > 10) {
			newHistory.splice(10)
		}
		searchHistory.value = newHistory
		// 保存到本地存储
		uni.setStorageSync('searchHistory', newHistory)
	}

	const loadSearchHistory = () => {
		try {
			const history = uni.getStorageSync('searchHistory')
			if (history) {
				searchHistory.value = history
			}
		} catch (error) {
			console.error('加载搜索历史失败:', error)
		}
	}

	const clearHistory = () => {
		searchHistory.value = []
		uni.removeStorageSync('searchHistory')
	}

	const handlePostClick = (post : PostBasicInfo) => {
		uni.navigateTo({
			url: `/pages/post/postDetail?id=${post.id}`
		})
	}

	const handleCircleClick = (circle : CircleBasicInfo) => {
		uni.navigateTo({
			url: `/pages/circle/circleDetail/circleDetail?id=${circle.id}`
		})
	}

	const handleUserClick = (user : any) => {
		uni.navigateTo({
			url: `/pages/author/authorDetail?id=${user.userId}`
		})
	}

	// 返回上一页
	const goBack = () => {
		uni.navigateBack()
	}
</script>

<style lang="scss" scoped>
	.search-page {
		min-height: 100vh;
		background-color: #f7f7f7;
	}

	.search-header {
		background: #FFFFFF;
		padding: 20rpx 24rpx;

		.search-bar {
			display: flex;
			align-items: center;
			gap: 20rpx;
			background: white;
			border-radius: 50rpx;
			padding: 16rpx 24rpx;
			position: relative;

			&.search-focused {
				box-shadow: 0 0 0 4rpx rgba(102, 126, 234, 0.2);
			}

			.back-button {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 60rpx;
				height: 60rpx;
				border-radius: 50%;
				transition: background-color 0.2s;

				&:active {
					background-color: #f0f0f0;
				}
			}

			.search-input-wrapper {
				flex: 1;
				display: flex;
				align-items: center;
				gap: 16rpx;
				max-width: 500rpx;
				/* 限制输入框最大宽度 */

				.search-icon {
					flex-shrink: 0;
				}

				.search-input {
					flex: 1;
					font-size: 28rpx;
					color: #333;
					border: none;
					outline: none;
					background: transparent;

					&::placeholder {
						color: #999;
					}
				}

				.clear-button {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 40rpx;
					height: 40rpx;
					border-radius: 50%;
					background-color: #f0f0f0;
					transition: background-color 0.2s;

					&:active {
						background-color: #e0e0e0;
					}
				}
			}
		}
	}

	.search-history,
	.hot-search {
		padding: 32rpx 24rpx;
		background: white;
		margin-bottom: 16rpx;

		.history-header,
		.hot-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 24rpx;

			.history-title,
			.hot-title {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
			}

			.history-clear {
				font-size: 28rpx;
				color: #999;
			}
		}

		.history-tags,
		.hot-tags {
			display: flex;
			flex-wrap: wrap;
			gap: 16rpx;

			.history-tag,
			.hot-tag {
				padding: 16rpx 24rpx;
				background: #f5f5f5;
				border-radius: 30rpx;
				font-size: 28rpx;
				color: #666;
			}

			.hot-tag {
				background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
				color: white;
			}
		}
	}

	.search-results {
		flex: 1;

		.result-tabs {
			display: flex;
			background: white;
			padding: 0 24rpx;
			border-bottom: 2rpx solid #f0f0f0;

			.tab-item {
				flex: 1;
				text-align: center;
				padding: 24rpx 0;
				font-size: 28rpx;
				color: #666;
				border-bottom: 4rpx solid transparent;
				transition: all 0.3s ease;

				&.active {
					color: #667eea;
					border-bottom-color: #667eea;
					font-weight: 600;
				}
			}
		}

		.result-content {
			.loading {
				padding: 60rpx 0;
				text-align: center;
			}

			.no-result {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 120rpx 0;

				.no-result-image {
					width: 200rpx;
					height: 200rpx;
					margin-bottom: 40rpx;
				}

				.no-result-text {
					font-size: 32rpx;
					color: #666;
					margin-bottom: 16rpx;
				}

				.no-result-tip {
					font-size: 28rpx;
					color: #999;
				}
			}

			.result-section {
				background: white;
				margin-bottom: 16rpx;

				.section-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 24rpx;
					border-bottom: 2rpx solid #f0f0f0;

					.section-title {
						font-size: 32rpx;
						font-weight: 600;
						color: #333;
					}

					.section-more {
						font-size: 28rpx;
						color: #667eea;
					}
				}
			}

			.circle-list,
			.user-list {
				background: white;
				padding: 24rpx;
			}
		}
	}
</style>